<template>
  <div class="user-posts-container">
    <!-- 发帖表单 -->
    <el-card class="publish-form">
      <h3>发表新帖</h3>
      <el-form @submit.prevent="createPost">
        <el-form-item label="标题">
          <el-input v-model="newPost.title" />
        </el-form-item>
        <el-form-item label="话题">
          <el-input v-model="newPost.topic" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="newPost.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-button type="primary" native-type="submit">发布</el-button>
      </el-form>
    </el-card>

    <!-- 加载提示 -->
    <div v-if="loading" class="loading-text">加载中...</div>

    <!-- 帧子列表 -->
    <div v-else>
      <el-card v-for="post in posts" :key="post.ID" class="post-item">
        <h4>{{ post.title }}</h4>
        <p><strong>话题：</strong>{{ post.topic }}</p>
        <p><strong>发布时间：</strong>{{ formatDate(post.CreatedAt) }}</p>
        <el-button @click="editPost(post)">编辑</el-button>
        <el-button @click="deletePost(post.ID)" type="danger">删除</el-button>
      </el-card>

      <!-- 分页 -->
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="loadPosts"
        class="pagination"
      />
    </div>

    <!-- 空状态提示 -->
    <div v-if="!loading && posts.length === 0" class="no-posts">
      暂无帖子，快去发表一篇吧！
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted} from 'vue'
import { onBeforeRouteUpdate } from 'vue-router'
import { useAuthStore } from '../store/auth'
import axios from '../axios'
import type { Post } from '../types/Article'
import { useRouter, useRoute } from 'vue-router'


const router = useRouter()
const authStore = useAuthStore()
const route = useRoute()

// 权限检查函数（抽象化处理）
const hasPermissionToDelete = (post: Post): boolean => {
  const userLevel = Number(authStore.level) || 0; // 安全转换
  console.log('当前用户等级:', userLevel);

  return post.authorID === authStore.userID || userLevel >= 4;
}

// 表单数据
const newPost = ref<Omit<Post, 'ID' | 'CreatedAt' | 'UpdatedAt' | 'DeletedAt' | 'likes'>>({
  title: '',
  topic: '',
  authorID: authStore.userID || 0,
  content: '',
})

// 当前帖子列表
const posts = ref<Post[]>([])
const total = ref<number>(0)
const pageSize = 5
const currentPage = ref<number>(1)
const loading = ref<boolean>(false)
const loadPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/posts', {
      params: {
        authorID: authStore.userID,
        page: currentPage.value,
        size: pageSize
      }
    })
    posts.value = response.data.posts
    total.value = response.data.total
  } catch (error) {
    console.error('加载帖子失败:', error)
    alert('加载帖子失败，请重试')
  } finally {
    loading.value = false
  }
}
// ✅ 每次进入页面都刷新
onMounted(() => {
  if (authStore.userID) {
    loadPosts()
  }
})
// ✅ 路由更新时也刷新（例如从 EditPost 返回）
onBeforeRouteUpdate(async (to, from, next) => {
  if (authStore.userID) {
    await loadPosts()
  }
  next()
})
// 创建帖子
const createPost = async () => {
  try {
    const response = await axios.post('/api/posts', newPost.value)
    posts.value.unshift(response.data)
    newPost.value = {
      ...newPost.value,
      title: '',
      topic: '',
      content: ''
    }
    alert('发帖成功')
  } catch (error) {
    console.error('发帖失败:', error)
  }
}

// 删除帖子
import { isTokenExpired } from '../utils/tokenUtils'; // 注意路径要根据你的 alias 配置调整

const deletePost = async (id: number) => {
  if (!confirm('确定要删除这篇帖子吗？')) return;

  try {
    // 获取当前要删除的帖子
    const post = posts.value.find(p => p.ID === id);
    if (!post) {
      alert('帖子不存在');
      return;
    }

    // ✅ 检查 token 是否存在或是否过期
    const token = localStorage.getItem('token');
    if (!token || isTokenExpired(token)) {
      alert('登录已过期，请重新登录');
      router.push({ name: 'Login' });
      return;
    }

    // ✅ 发起删帖请求
    await axios.delete(`/api/posts/${id}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    // ✅ 快速更新 UI
    posts.value = posts.value.filter(post => post.ID !== id);

    // ✅ 再次加载确保数据同步（可选）
    // await loadPosts();

    alert('删除成功');
  } catch (error) {
    let errorMessage = '未知错误';

    if (error instanceof Error) {
      errorMessage = error.message;
    } else if (typeof error === 'object' && error !== null && 'response' in error) {
      const err = error as { response?: { data?: string } };
      errorMessage = err.response?.data || '服务器返回了错误';
    }

    console.error('❌ 删除失败:', errorMessage);
    alert(`删除失败：${errorMessage}`);
  }
};
const editPost = (post: Post) => {
  router.push({ name: 'EditPost', params: { id: post.ID }, query: { editing: 'true' } })
}

// 格式化时间
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

onMounted(() => {
  if (authStore.userID) {
    loadPosts()
  }
})
</script>

<style scoped>
.user-posts-container {
  max-width: 900px;
  margin: 60px auto;
  padding: 20px;
}

.publish-form {
  margin-bottom: 40px;
}

.post-item {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-left: 5px solid #409EFF;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.loading-text {
  text-align: center;
  font-size: 16px;
  color: #666;
  margin-top: 20px;
}

.no-posts {
  text-align: center;
  font-size: 16px;
  color: #999;
  margin-top: 20px;
}
</style>